package edu.rit.hvz.android;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import edu.rit.hvz.android.DataLayer.ServerDatabaseConnection;

import android.app.Activity;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

/**
 * This is the class that is used to view the user's profile. This class
 * extends PlayerProfile in order to provide support for updating the player profile
 * photo.
 * @author Colton
 *
 */
public class Profile extends PlayerProfile {
	
	// Variables used for taking a photo.
	private static final int REQUEST_CODE = 1;
	private static final int TAKE_PHOTO = 2;
	private Bitmap bitmap;
	private ImageView profilePicture = null;
	private Uri mImageUri;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		profilePicture = (ImageView) findViewById(R.id.profilePic);
		registerForContextMenu(profilePicture);
		
		profilePicture.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				openContextMenu(v);
			}
		});
		
	}
	
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
	    super.onCreateContextMenu(menu, v, menuInfo);
	    menu.add(0, TAKE_PHOTO, 0, "Change Profile Picture");
	}
	
	public void onRestoreInstanceState(Bundle saved) {
	    super.onRestoreInstanceState(saved);
	    profilePicture = (ImageView)saved.get("profilePicture");
	    if (saved.containsKey("mImageUri")) {
	        mImageUri = Uri.parse(saved.getString("mImageUri"));
	    }
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, TAKE_PHOTO, 0, "Change Profile Picture");
        return super.onCreateOptionsMenu(menu);
        
    }
	
	 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
    	case TAKE_PHOTO:
    		pickImage();
    		return true;
    	case R.id.settings:
			this.startActivity(new Intent(this, Preferences.class));
			return true;
        }
        return false;
    }
	 
	 public boolean onContextItemSelected(MenuItem item) {
			switch (item.getItemId()) {
			case TAKE_PHOTO:
				pickImage();
				return true;
			}
			return super.onContextItemSelected(item);
		}
	
	public void pickImage() {
		 Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		    File photo = null;
		    try
		    {
		        // place where to store camera taken picture
		        photo = this.createTemporaryFile("picture", ".jpg");		        
		        mImageUri = Uri.fromFile(photo);
		        photo.delete();
			    //intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);   ****Enable to capture full image**** hass issues yet
			    //start camera intent
			    startActivityForResult(intent, TAKE_PHOTO);
		    }
		    catch(Exception e)
		    {		       
		        Toast.makeText(this, "Please check SD card! Image shot is impossible!", 10000).show();		    
		    }
		    
	}
	
	private void handleSmallCameraPhoto(Intent intent) {
		if (bitmap != null) {
			bitmap.recycle();
		}
	    Bundle extras = intent.getExtras();
	    bitmap = (Bitmap) extras.get("data");
	    profilePicture.setImageBitmap(bitmap);
	    
	    // Convert the Bitmap to a byte array and store it to the db
	    
	}
	
	private File createTemporaryFile(String part, String ext) throws Exception
	{
	    File tempDir= Environment.getExternalStorageDirectory();
	    tempDir=new File(tempDir.getAbsolutePath()+"/.temp/");
	    if(!tempDir.exists())
	    {
	        tempDir.mkdir();
	    }
	    return File.createTempFile(part, ext, tempDir);
	}
	
	private void grabImage(ImageView imageView)
	{
	    this.getContentResolver().notifyChange(mImageUri, null);
	    ContentResolver cr = this.getContentResolver();
	    Bitmap bitmap;
	    try
	    {
	        bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, mImageUri);
	        imageView.setImageBitmap(bitmap);
	    }
	    catch (Exception e)
	    {
	        Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();	        
	    }
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == TAKE_PHOTO && resultCode == Activity.RESULT_OK)
	       //... some code to inflate/create/find appropriate ImageView to place grabbed image
	       //this.grabImage(profilePicture); Gets full sized image but has lots of other issues yet
			handleSmallCameraPhoto(data);

		super.onActivityResult(requestCode, resultCode, data);
	}

}
